﻿<template>
  <a-modal
    title="新增备料"
    width="90vw"
    :visible="visible"
    dialogClass="zero-modal"
    @cancel="handleCancel">
    <a-spin :spinning="confirmLoading">
      <div class="prepare-manage-modal-content">
        <div class="form-view">
          <a-form :form="form">
            <a-row>
              <a-col :md="8" :sm="24">
                <a-form-item label="单据号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input disabled v-decorator="['OrderNo',{rules:[{required:true,message:'单据号不可为空！'}]}]" />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="叫料站点" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input v-show="false" v-decorator="['takeMaterialsSiteId',{rules:[{required:true,message:'请选择叫料站点！'}]}]" />
                  <station-select v-model="stationArr" :get-lines="getLines" :get-stations="getStations" @change="onChangeStation" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div class="action-view">
          <a-button type="primary" icon="plus" @click="openChoose">
            添加物料
          </a-button>
        </div>
        <div class="list-view" ref="listWrapper">
          <!-- 注意scroll.x的值 -->
          <a-table v-if="th" :data-source="list" :columns="columns" :rowKey="tableKey" :pagination="false" :scroll="{x:1100,y:th}">
            <template slot="index" slot-scope="text,record,index">{{index+1}}</template>
            <template slot="action" slot-scope="text,record,index">
              <a-button type="danger" size="small" @click.stop="cancelListItem(index)">删除</a-button>
            </template>
            <span slot="materialTyleSlot" slot-scope="text">{{ 'material_type' | dictType(text) }}</span>
            <template slot="inputCell" slot-scope="text,record,index">
              <a-input-number v-model="record.orderQuantity" :min="0" />
            </template>
            <template slot="dateCell" slot-scope="text,record,index">
              <a-date-picker :value="record.requireTime" value-format="YYYY-MM-DD" format="YYYY-MM-DD" @change="onChangeRequireDate(index,$event)" />
            </template>
          </a-table> 
        </div>
      </div>
    </a-spin>
    
    <choose-modal :visible.sync="chooseVisible" @callback="chooseBack" />
    
    <template slot="footer">
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" :loading="confirmLoading" @click="handleSubmit" :disabled="!list.length">确认</a-button>
    </template>
  </a-modal>
</template>

<script>
  import ChooseModal from './chooseMaterials.vue'
  import { PrePareManageAdd,GetBillNumber } from '@/api/modular/main/prePareManage'
  import StationSelect from '@/components/StationSelect.vue'
  import { GetLines,GetStations } from '@/api/modular/main/LesStationManage'
  export default {
    components:{ChooseModal,StationSelect},
    data () {
      return {
        getLines:GetLines,
        getStations:GetStations,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 18 }
        },
        visible: false,
        confirmLoading: false,
        stationArr:[],
        th:0,
        tableKey:'materialName',
        list:[],
        columns:[
          { title: '序号', key: 'index', width: 70, align:'center', fixed:"left", scopedSlots: { customRender: 'index' }},
          { title: '物料类型', dataIndex: 'materialType', width: 120, scopedSlots: { customRender: 'materialTyleSlot' }},
          { title: '物料编码', dataIndex: 'materialNo', key: 'materialNo' },
          { title: '物料名称', dataIndex: 'materialName', key: 'materialName' },
          { title: '批次', dataIndex: 'materialBatch', key: 'materialBatch', width: 180 },
          { title: '数量', key: 'orderQuantity', scopedSlots: { customRender: 'inputCell' }, width: 220, align:'center'},
          { title: '需求日期', key: 'requireTime', scopedSlots: { customRender: 'dateCell' }, width: 220, align:'center'},
          { title: '操作', key: 'action', width: 80, align:'center', fixed:"right", scopedSlots: { customRender: 'action' }}
        ],
        chooseVisible:false
      }
    },
    beforeCreate(){
      this.form = this.$form.createForm(this)
    },
    methods: {
      // 初始化方法
      add (record) {
        this.visible = true
        this.$nextTick(() => {
          this.th = this.$refs.listWrapper.clientHeight - 60
          this.getInitData()
        });
      },
      getInitData(){
        this.confirmLoading = true;
        GetBillNumber().then((d1)=>{
          this.form.setFieldsValue({OrderNo:(d1.data.takeMaterialsNo || '')})
          this.confirmLoading = false;
        }).catch(()=>{
          this.confirmLoading = false;
        })
      },
      onChangeStation(arr){
        this.form.setFieldsValue({takeMaterialsSiteId:arr[1]})
      },
      chooseBack(arr){
        let newArr = [], reCount = 0;
        arr.forEach((item)=>{
          let f = false;
          for (let i=0;i<this.list.length;i++) {
            if (this.list[i][this.tableKey] === item[this.tableKey]) {
              reCount++;
              f = true
              break;
            }
          }
          if (!f) {
            let _obj = {...item}
            _obj.orderQuantity = 0
            _obj.requireTime = ''
            newArr.push(item)
          }
        })
        this.list = [].concat(newArr,this.list)
        if (reCount) {
          this.$message.warning(`${reCount}笔数据已存在，未添加！`);
        }
      },
      cancelListItem(index){
        this.list.splice(index,1)
      },
      onChangeRequireDate(index,val){
        let arr = this.list.map((item,i)=>{
          if (i===index) {
            item.requireTime=val
          } else {
            if (!item.requireTime) {
              item.requireTime=val
            }
          }
          return item
        })
        this.list = arr
      },
      interalNumberValidate(val){
        let res = 0
        if (!val) {
          res = 1  //数量必填且大于0
        } else if (Number(val)!==parseInt(val)) {
          res = 2  //只能是整数
        }
        return res
      },
      checkBeforeSubmit() {
        let res = true, msg = '';
        for (let i=0;i<this.list.length;i++) {
          let numberTag = this.interalNumberValidate(this.list[i].orderQuantity)
          if (numberTag!==0) {
            res = false
            if (numberTag===1) {
              msg = `第${i+1}行，数量必填且大于0！`
            } else if (numberTag===2) {
              msg = `第${i+1}行，数量只能是整数！`
            }
            break;
          }
          if (!this.list[i].requireTime) {
            res = false
            msg = `第${i+1}行，需求日期必填！`
            break;
          }
        }
        if (!res) {
          this.$message.warning(msg);
        }
        return res
      },
      /**
       * 提交表单
       */
      handleSubmit () {
        this.form.validateFields((errors, values) => {
          if (!errors) {
            let f = this.checkBeforeSubmit()
            if (f) {
              this.confirmLoading = true
              let params = {...values,...{WmsAssembleOrderDetails:this.list}}
              PrePareManageAdd(params).then(()=>{
                this.confirmLoading = false
                this.handleCancel()
                this.$emit('ok')
              }).catch(()=>{
                this.confirmLoading = false
              })
            }
          } 
        })
      },
      handleCancel () {
        this.visible = false
        this.th = 0
        this.list = []
        this.chooseVisible = false
      },
      openChoose(){
        this.chooseVisible = true
      }
    }
  }
</script>
<style lang="less" scoped>
.prepare-manage-modal-content{
  height: 70vh;
  display: flex;
  flex-direction: column;
  .form-view,.action-view{
    flex-shrink: 0;
  }
  .form-view{
    background-color: #F3F7FA;
    padding-top: 20px;
  }
  .action-view{
    padding: 8px 16px;
  }
  .list-view{
    flex-grow: 1;
    padding: 0 16px;
    overflow: auto;
  }
}
</style>